<template>
  <!--图片 -->
  <view class="up-page">
    <!--图片-->
    <view class="show-box" v-for="(item, index) in imageList" :key="index">
      <image
        class="showImg"
        :src="item"
        :data-src="image"
        @tap="previewImage(item)"
      ></image>
      <view class="delect-icon" @tap="delect(index)">
        <view class="closeBox">
        <uv-icon name="close" color="#fff" size="17rpx"></uv-icon>

        </view>
      </view>
    </view>
    <view v-if="addImgShow" @tap="chooseVideoImage" class="">
      <slot name="upbox">
        <view class="box-mode">
          <uv-icon name="tianchong2" custom-prefix="custom-icon" size="24"></uv-icon>
          <p class="txt">上传图片</p>
        </view>
      </slot>
    </view>
  </view>
</template>
<script lang="ts" setup>
import { ref, onUnmounted } from "vue";
// 请求基地址
const baseURL = import.meta.env.VITE_SERVER_BASEURL;
// 定义响应式数据

const addImgShow = ref(true);
// 本地图片列表
const imageList = ref([]);
// 上传后服务器返回的列表
const uploadList = ref([]);

const sourceType = ref(["拍摄", "相册", "拍摄或相册"]);
const sourceTypeIndex = ref(2);
const emit = defineEmits("uploadSuccess");
const cameraList = ref([
  { value: "back", name: "后置摄像头", checked: "true" },
  { value: "front", name: "前置摄像头" },
]);
const cameraIndex = ref(0);
const maxCount = ref(3);

const props = defineProps({
  maxCount: {
    type: Number,
    default: 6,
  },

});
// 生命周期钩子（onMounted, onUnmounted等）
onUnmounted(() => {
  imageList.value = [];
  sourceTypeIndex.value = 2;
  sourceType.value = ["拍摄", "相册", "拍摄或相册"];
});
// 方法
function chooseVideoImage() {
  uni.showActionSheet({
    title: "选择上传类型",
    itemList: ["图片"], // 注意：这里只有'图片'，如果需要视频应添加'视频'
    success: (res) => {
      if (res.tapIndex === 0) {
        chooseImages();
      }
      // 注意：原代码中没有实现chooseVideo，这里未添加
    },
  });
}
function chooseImages() {
  uni.chooseImage({
    count: props.maxCount,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      if (imageList.value.length + res.tempFilePaths.length >= props.maxCount) {
        addImgShow.value = false;
        res.tempFilePaths.length = props.maxCount - imageList.value.length;
        imageList.value = [...imageList.value, ...res.tempFilePaths];
        uploadFileFn(res.tempFilePaths)
      } else {
        imageList.value = [...imageList.value, ...res.tempFilePaths];
        uploadFileFn(res.tempFilePaths)
      }
    },
  });
}
// 上传方法
const uploadFileFn =(files:any[])=>{
  const uploadTasks =  files.map((file: any, index: number) => {
     return new Promise((resolve, reject) => {
      uni.uploadFile({
          url: baseURL + "/commentApp/common/uploadFile", // 仅为示例，非真实的接口地址
          filePath: file,
          name: "file",
          formData: {
            user: "test",
          },
          success: (res) => {
            let result = JSON.parse(res.data)
            uploadList.value.push(result.data)
            resolve(res.data)
          },
        });

     })
  })

  Promise.all(uploadTasks)
     .then((res) => {
      console.log('上传成功', res)
       // 上传成功后的操作
     })
     .catch((err) => {
       console.log('上传失败', err)
      // 上传失败后的操作
     })

}
const  previewImage =(e)=> {
  uni.previewImage({
    // current: e.currentTarget.dataset.url || e, // 假设你通过某种方式传递了图片的URL
    current: e, // 假设你通过某种方式传递了图片的URL
    urls: imageList.value,
  });
}
// 删除图片的函数
const  delect =(index)=> {
  uni.showModal({
    title: "提示",
    content: "是否要删除该图片",
    success: (res) => {
      if (res.confirm) {
        // 使用splice方法删除图片，注意需要访问.value
        imageList.value.splice(index, 1);
        if (imageList.value.length == props.maxCount) {
          addImgShow.value = false;
        } else {
          addImgShow.value = true;
        }
      }
    },
  });
}

defineExpose({imageList,uploadList})
</script>

<style lang="scss">
/* 统一上传后显示的盒子宽高比 */
.box-mode {
  width: 154rpx;
  height: 154rpx;
  background: #f9f9f9;
  border-radius: 15rpx;
  border: 2rpx solid #dcdde1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .txt {
    font-weight: 400;
    font-size: 23rpx;
    color: #595a5b;
    line-height: 38rpx;
    text-align: center;
  }
}
.showImg {
  width: 100%;
  height: 100%;
  border-radius: 15rpx;
}
.up-page {
  display: flex;
  flex-wrap: wrap;
  display: flex;
  width: 100%;
  .show-box:nth-child(3n) {
    margin-right: 0;
  }
  .show-box {
    position: relative;
    margin-bottom: 24rpx;
    margin-right: 24rpx;
    overflow: hidden;

    @extend .box-mode;
    .delect-icon {
      height: 76rpx;
      width: 76rpx;
      background: #000;
      opacity: 0.5;
      border-radius: 50%;
      position: absolute;
      right: -38rpx;
      top: -38rpx;
      z-index: 1000;

      .closeBox{
        position: absolute;
        bottom: 12rpx;
        left: 12rpx;
      }
    }
  }
}
</style>
